import moment from "moment";
 import {
 	Storage_Key,
 	UserJobsType,
 	UserJobMenuAuth,
 	DicList,
	Platform
 } from '@/static/config.js'
 import {
 	get,
 	set,
 	del,
 	clear,
 	userToken
 } from '@/common/storage'
const CryptoJS = require("crypto-js");
 // 获取数据字典
 export function getDic(itemname) {
 	return DicList[itemname]
 }

 // 获取平台用户授权模块
 export const GetAuthModule = (val) => {
 	let webUserInfo = get(Storage_Key.web_user_info, true);
 	let wxUserInfo = get(Storage_Key.user_info, true);
 	let userjobs = [UserJobsType[1].key]; // 默认游客
 	if (!!webUserInfo) { // 平台账号
 		userjobs = (!!webUserInfo.job) ? webUserInfo.job : [UserJobsType[1].key]; // 根据平台角色判断
 		// userjobs = [UserJobsType[4].key]; // 管理员
 	} else if (!!wxUserInfo) {
 		userjobs = [UserJobsType[2].key]; // 微信用户
 	}
 	let result = [];
 	if (val) { // 指定模块
 		let indexTabs = UserJobMenuAuth.find(e => e.type == val).children;
 		indexTabs.forEach(e => {
 			if (e.jobs.some(item => userjobs.includes(item))) {
 				result.push(e);
 			}
 		})
 	} else { // 全部
 		UserJobMenuAuth.forEach(ie => {
 			let child = [];
 			ie.children.forEach(e => {
 				if (e.jobs.some(item => userjobs.includes(item))) {
 					child.push(e);
 				}
 			})
 			result.push({
 				type: ie.type,
 				children: child
 			})
 		})
 	}
 	return result;
 }

 // 获取平台用户职务key信息 by roles
 export const GetUserJobKeys = (val) => {
 	let keys = [];
 	if (val) {
 		let roles = val.map(item => {
 			return item.name;
 		})
 		let result = UserJobsType.filter(item => roles.includes(item.text));
 		if (!!result) {
 			keys = result.map(im => im.key);
 		}
 	}
 	return keys;
 }
 // 获取平台用户职务text信息
 export const GetUserJobTexts = (val) => {

 	let infos = [];
 	if (val) {
 		let jobs = val.split(',');
 		let result = UserJobsType.filter(item => jobs.includes(item.key));
 		if (!!result) {
 			infos = result.map(im => im.text.toString());
 		}
 	}
 	return infos;
 }
 // 判断字符串是否是JSON格式
 export const IsJson = (val) => {
 	if (isNaN(Number(val))) {
 		try {

 			// JSON.parse(val);
 			JSON.parse('{"cardcode" : "123456", "cardname" : "卡片1"}');
 			return true;
 		} catch (e) {
 			return false;
 		}

 	} else {}
 	return false;
 }

 // 两小时内 - 显示新
 // export const GetLimitTime = (val) => {
 // 	let time = false;
 // 	let timediff_hours = (moment()).diff(moment(val).format(), 'minutes'); // hours不准
 // 	if (timediff_hours <= 120) {
 // 		time = true;
 // 	}
 // 	console.log(time);
 // 	return time;
 // }

 // 联系人名字格式化
 export const GetLinkpersonFormat = (val) => {
 	let name = "***";
 	if (val.length > 1) {
 		name = val.substr(0, 1) + "**";
 	}
 	return name;
 }

 //加载显示
 function loadToShow(msg = '加载中') {
 	uni.showToast({
 		title: msg,
 		icon: 'loading'
 	})
 }

 //加载隐藏
 function loadToHide() {
 	uni.hideToast()
 }

 // 提示框
 function modelShow(
 	callback = () => {},
 	title = '提示',
 	content = '确认执行此操作吗?',
 	showCancel = true,
 	cancelText = '取消',
 	confirmText = '确定'
 ) {
 	uni.showModal({
 		title: title,
 		content: content,
 		showCancel: showCancel,
 		cancelText: cancelText,
 		confirmText: confirmText,
 		cancelText: cancelText,
 		success: function(res) {
 			if (res.confirm) {
 				// 用户点击确定操作
 				// setTimeout(() => {
 				callback()
 				// }, 500)
 			} else if (res.cancel) {
 				// 用户点击取消操作
 			}
 		}
 	})
 }

 // 统一跳转接口,拦截未登录路由，navigator标签现在默认没有转场动画，所以用view
 export const NavTo = (url, istab) => {
 	// if (!this.hasLogin) {
 	// 	url = '/pages/public/login';
 	// }
 	if (istab) {
 		uni.switchTab({
 			url: url
 		});
 	} else {
 		uni.navigateTo({
 			url
 		})
 	}
 }

 // 车牌底色
 export const GetCardColor = (val) => {
 	let result = {
 		index: 0,
 		color: 'card-blue'
 	}
 	switch (val) {
 		case '蓝牌':
 			result = {
 				index: 0,
 				color: 'card-blue'
 			}
 			break;
 		case '黄牌':
 			result = {
 				index: 1,
 				color: 'card-yellow'
 			}
 			break;
 		case '绿牌':
 			result = {
 				index: 2,
 				color: 'card-green'
 			}
 			break;
 		case '白牌':
 			result = {
 				index: 3,
 				color: 'card-white'
 			}
 			break;
 		case '黑牌':
 			result = {
 				index: 4,
 				color: 'card-black'
 			}
 			break;
 	}
 	return result;
 }

 // 车辆进出状态
 export const GetRecordState = val => {
 	let result = {};
 	// if (val) {
 	switch (val) {
 		case "0": // 出场
 			result = {
 				style: "color:#07D2C6;border-color:#07D2C6;",
 				stylefill: "color:#ffffff;background-color:#07D2C6;",
 				value: "出场"
 			}
 			break;
 		case "1": // 入场
 			result = {
 				style: "color:#e0620d;border-color:#e0620d;",
 				stylefill: "color:#ffffff;background-color:#e0620d;",
 				value: "入场"
 			}
 			break;
 		default:
 			result = {
 				style: "color:#a3a3a3;border-color:#a3a3a3;",
 				stylefill: "color:#ffffff;background-color:#a3a3a3;",
 				value: "未知"
 			}
 			break;
 	}
 	// }
 	return result;
 }

 // 审批状态 - 车辆预约
 export const GetApproveState = val => {
 	let result = {};
 	// 0审批通过/1已失效/2待审批/3审批不通过
 	switch (val) {
 		case "0": // 通过
 			result = {
 				style: "color:#07D2C6;border-color:#07D2C6;",
 				stylenoborder: "color:#07D2C6;",
 				stylefill: "color:#ffffff;background-color:#07D2C6;",
 				value: "通过"
 			}
 			break;
 		case "1": // 已失效（车辆入园后失效）
 			result = {
 				style: "color:#a3a3a3;border-color:#a3a3a3;",
 				stylenoborder: "color:#a3a3a3;",
 				stylefill: "color:#ffffff;background-color:#a3a3a3;",
 				value: "已失效"
 			}
 			break;
 		case "2": // 待审批
 			result = {
 				style: "color:#e0620d;border-color:#e0620d;",
 				stylenoborder: "color:#e0620d;",
 				stylefill: "color:#ffffff;background-color:#e0620d;",
 				value: "待审批"
 			}
 			break;

 		case "3": // 拒绝
 			result = {
 				style: "color:#FF2600;border-color:#FF2600;",
 				stylenoborder: "color:#FF2600;",
 				stylefill: "color:#ffffff;background-color:#FF2600;",
 				value: "拒绝"
 			}
 			break;
 		default:
 			result = {
 				style: "color:#a3a3a3;border-color:#a3a3a3;",
 				stylenoborder: "color:#a3a3a3;",
 				stylefill: "color:#ffffff;background-color:#a3a3a3;",
 				value: "未知"
 			}
 			break;
 	}
 	return result;
 }

 // 审批状态 - 车辆
 export const GetCarApproveState = val => {
 	let result = {};
 	// 0：未审核，1：已审核，2：未通过
 	switch (val) {
 		case "0": // 待审批
 			result = {
 				style: "color:#e0620d;border-color:#e0620d;",
 				stylenoborder: "color:#e0620d;",
 				stylefill: "color:#ffffff;background-color:#e0620d;",
 				value: "待审批"
 			}
 			break;
 		case "1":
 			result = {
 				style: "color:#07D2C6;border-color:#07D2C6;",
 				stylenoborder: "color:#07D2C6;",
 				stylefill: "color:#ffffff;background-color:#07D2C6;",
 				value: "通过",
 			}
 			break;
 		case "2": // 未通过
 			result = {
 				style: "color:#FF2600;border-color:#FF2600;",
 				stylenoborder: "color:#FF2600;",
 				stylefill: "color:#ffffff;background-color:#FF2600;",
 				value: "未通过"
 			}
 			break;
 		default:
 			result = {
 				style: "color:#a3a3a3;border-color:#a3a3a3;",
 				stylenoborder: "color:#a3a3a3;",
 				stylefill: "color:#ffffff;background-color:#a3a3a3;",
 				value: "未知"
 			}
 			break;
 	}
 	return result;
 }


 //车架号验证 
 export const OnCheckVIN = vin => {
 	if (vin.length > 0 && vin.length != 17) {
 		return false;
 	} else {
 		var vinVal = vin.toUpperCase(); // 将字符串转换成大写
 		//document.getElementById("vin_"+k).value = vinVal;				
 		var charToNum = {
 			'A': 1,
 			'B': 2,
 			'C': 3,
 			'D': 4,
 			'E': 5,
 			'F': 6,
 			'G': 7,
 			'H': 8,
 			'J': 1,
 			'K': 2,
 			'L': 3,
 			'M': 4,
 			'N': 5,
 			'P': 7,
 			'R': 9,
 			'S': 2,
 			'T': 3,
 			'U': 4,
 			'V': 5,
 			'W': 6,
 			'X': 7,
 			'Y': 8,
 			'Z': 9
 		};
 		var obj = 0;
 		var arr = new Array();
 		for (var i = 0; i < vinVal.length; i++) {
 			var temp = vinVal.charAt(i);
 			if (charToNum[temp]) {
 				arr[i] = charToNum[temp];
 			} else {
 				arr[i] = Number(temp);
 			}
 			if (i == 8) {
 				arr[i] = vinVal.charAt(i);
 			}
 		};
 		var a1 = 8;
 		for (var i = 0; i < 7; i++) {
 			obj += Number(arr[i]) * a1;
 			a1--;
 		};
 		obj += Number(arr[7]) * 10;
 		var a2 = 9;
 		for (var i = 9; i < 17; i++) {
 			obj += Number(arr[i]) * a2;
 			a2--;
 		};
 		var result = Number(obj) % 11;
 		if (parseInt(result) === 10) {
 			result = 'X';
 		}
 		if (result == arr[8]) { //成功					  
 			return true;
 		} else { //失败                                     
 			return false;
 		}
 	}
 };
 /************************************* 时间格式化 *************************************/
 // export function FormatDate(time) {
 // 	if (time == 0 || time == null || time == "")
 // 		return '未设置';
 // 	return moment(time)
 // 		.locale("zh-cn")
 // 		.format("YYYY-MM-DD");
 // }
 export function FormatDateTime(time) {
 	if (time == 0 || time == null || time == "")
 		return '未设置';
 	return moment(time)
 		.locale("zh-cn")
 		.format("YYYY-MM-DD HH:mm:ss").toString();
 }
 
 export function formatDate(date, fmt) {
 	if (/(y+)/.test(fmt)) {
 		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
 	}
 	let o = {
 		'M+': date.getMonth() + 1,
 		'd+': date.getDate(),
 		'h+': date.getHours(),
 		'm+': date.getMinutes(),
 		's+': date.getSeconds()
 	};
 	for (let k in o) {
 		if (new RegExp(`(${k})`).test(fmt)) {
 			let str = o[k] + '';
 			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
 		}
 	}
 	return fmt;
 };

 function padLeftZero(str) {
 	return ('00' + str).substr(str.length);
 };



/**
 * 生成sign
 * @param {Object} method get/post
 * @param {Object} timestamp 十位时间戳
 * @param {Object} data 接口参数
 * @example 示例 get  Timestamp1733801236{test=123&pageIndex=1&pageSize=100}zysc
 * @example 示例 post Timestamp1733801236{"pageIndex":"1","pageSize":"100"}zysc
 */
export function GenerateToken(method, timestamp, data) {
	let encryptStr = "";

	if (timestamp.toString().length != 10) {
		return false; //时间戳长度应为10
	}
	if (!data || typeof data !== 'object') { //无参数时用{}
		encryptStr = "Timestamp" + timestamp + "{" + "}" + Platform.api_stp_signkey;
	} else {
		if (method === 'GET' || method === 'get' || method === 'Get') {
			let paramstr = "";
			Object.keys(data).forEach(e => {
				// let value = isChinese(data[e])?encodeURIComponent(data[e]):data[e];
				paramstr = paramstr + e + "=" + encodeURIComponent(data[e]) + "&";
			})
			paramstr = paramstr.slice(0, -1); //去掉最后的&字符
			encryptStr = "Timestamp" + timestamp + "{" + paramstr + "}" + Platform.api_stp_signkey;
		} else if (method === 'POST' || method === 'post' || method === 'Post') {

			let jsonstr = JSON.stringify(data, null, null); //去除数据中可能存在的空格
			jsonstr = jsonstr.replaceAll(/\s+/g, '');
			encryptStr = "Timestamp" + timestamp + encodeURIComponent(jsonstr) + Platform.api_stp_signkey;
		} else {
			encryptStr = "Timestamp" + timestamp + "{" + "}" + Platform.api_stp_signkey;;
		}
	}

	return md5DigestAsHex(encryptStr)
}

// md5加密
function md5DigestAsHex(message) {
	return CryptoJS.MD5(message).toString(CryptoJS.enc.Hex).toLowerCase();
}

// 判断字符是否是中文
function isChinese(str) {
	return /[\u4e00-\u9fa5]/.test(str);
}